package com.tianhui.consignortwofei.mvp.ui.activity;

import android.text.TextUtils;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.CustomProgressDialog;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.interf.IChartViewInfo;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.ChartViewInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.DriverCarStatisticalInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.OrderStatisticalInfo;
import com.tianhui.consignortwofei.mvp.model.enty.statistics.StatisticsDataInfo;
import com.tianhui.consignortwofei.widget.BarChartView;
import com.tianhui.consignortwofei.widget.LineChartView;
import com.tianhui.consignortwofei.widget.PieChartView;
import com.tianhui.consignortwofei.widget.StatisticsDataView;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2021/2/22
 * @description
 **/
public class StatisticsActivity extends BaseActivity {
    @BindView(R.id.activity_statistics_statisticsDataView)
    StatisticsDataView mStatisticsDataView;
    @BindView(R.id.activity_statistics_lineCharView)
    LineChartView mLineChartView;
    @BindView(R.id.activity_statistics_driverBarCharView)
    BarChartView mDriverBarChartView;
    @BindView(R.id.activity_statistics_carBarCharView)
    BarChartView mCarBarChartView;
    @BindView(R.id.activity_statistics_orderPieCharView)
    PieChartView mOrderPieChartView;

    @BindView(R.id.activity_statistics_amountPieCharView)
    PieChartView mAmountPieChartView;
    private UserInfoModel mModel;
    private Map<Integer, List<OrderStatisticalInfo>> orderResultList = new HashMap<>();
    private Map<Integer, DriverCarStatisticalInfo> driverCarResultList = new HashMap<>();
    private List<String> dateList = new ArrayList<>();

    private StatisticsDataInfo statisticsDataInfo = new StatisticsDataInfo();
    private int currentWeek = 1;

    private CustomProgressDialog mDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_statistics;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public String getToolbarSubtitle() {
        return "数据详情";
    }

    @Override
    public void onSubtitleClick() {
        openActivity(StatisticsDataActivity.class);
    }

    @Override
    public String getToolbarTitle() {
        return "数据展示";
    }

    @Override
    public void init() {
        mModel = new UserInfoModel();
        mDialog = new CustomProgressDialog(this);

        initDateList();

    }

    private void initDateList() {
        showDialog();
        dateList.clear();
        orderResultList.clear();
        driverCarResultList.clear();
        String date;
        int amount = currentWeek * 7 - 1;
        for (int i = 0; i < 7; i++) {
            SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
            Date beginDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginDate);
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + (i - amount));
            Date endDate = null;
            try {
                endDate = dft.parse(dft.format(calendar.getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            date = dft.format(endDate);
            dateList.add(date);
            requestOrderStatisticsInfo(i, date);
            requestDriverCarStatisticsInfo(i, date);
        }

    }

    private void requestOrderStatisticsInfo(int index, String date) {
        Map<String, String> map = new HashMap<>();
        map.put("dates", date);
        mModel.orderStatisticsInfoModel(this, map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<OrderStatisticalInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<OrderStatisticalInfo>> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    orderResultList.put(index, commonResponse.getData());
                    int size = orderResultList.size();
                    if (size == 7) {
                        processOrderStatisticsInfo();
                    }

                } else {
                    showToast(date + "--" + commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(date + "--" + e.message);
            }
        });

    }

    private void processOrderStatisticsInfo() {

        List<IChartViewInfo> orderStatisticsInfoList = new ArrayList<>();
        List<IChartViewInfo> allOrderStatisticsInfoList = new ArrayList<>();
        List<IChartViewInfo> allOrderAmountStatisticsInfoList = new ArrayList<>();
        ChartViewInfo resultInfo;
        ChartViewInfo allOrderResultInfo;
        ChartViewInfo allAmountResultInfo;
        OrderStatisticalInfo info;
        OrderStatisticalInfo TJInfo = null;
        OrderStatisticalInfo HBInfo = null;
        int resultSize = orderResultList.size();
        for (int i = 0; i < resultSize; i++) {
            resultInfo = new ChartViewInfo();
            List<OrderStatisticalInfo> list = orderResultList.get(i);
            int size = list.size();
            if (list != null && size > 0) {
                for (int j = 0; j < size; j++) {
                    info = list.get(j);
                    if (!TextUtils.isEmpty(info.belongarea) && info.belongarea.equals("1")) {
                        HBInfo = info;
                    } else if (!TextUtils.isEmpty(info.belongarea) && info.belongarea.equals("2")) {
                        TJInfo = info;
                    }

                }
                if (TJInfo != null && HBInfo != null) {
                    resultInfo.value = new BigDecimal(TJInfo.totalNow).add(new BigDecimal(HBInfo.totalNow)).toString();
                    resultInfo.label = dateList.get(i);
                    orderStatisticsInfoList.add(resultInfo);

                }
            }
        }
        mLineChartView.setLineChartData(orderStatisticsInfoList);
        if (TJInfo != null && HBInfo != null) {
            String orderTotalValue;
            String totalOrderValue;
            totalOrderValue = new BigDecimal(TJInfo.total).add(new BigDecimal(HBInfo.total)).toString();

            orderTotalValue = new BigDecimal(TJInfo.total).divide(new BigDecimal(totalOrderValue), 3, BigDecimal.ROUND_HALF_UP).toString();

            LogUtil.print(orderTotalValue);
            allOrderResultInfo = new ChartViewInfo();
            allOrderResultInfo.value = orderTotalValue;
            allOrderResultInfo.label = "天津：" + TJInfo.total;
            allOrderStatisticsInfoList.add(allOrderResultInfo);

            allOrderResultInfo = new ChartViewInfo();
            allOrderResultInfo.value = new BigDecimal("1").subtract(new BigDecimal(orderTotalValue)).toString();
            allOrderResultInfo.label = "河北：" + HBInfo.total;
            allOrderStatisticsInfoList.add(allOrderResultInfo);

            mOrderPieChartView.setPieChartData(allOrderStatisticsInfoList);


            String amountTotalValue;
            String totalAmountValue;
            totalAmountValue = new BigDecimal(TJInfo.amountTotal).add(new BigDecimal(HBInfo.amountTotal)).toString();

            amountTotalValue = new BigDecimal(TJInfo.amountTotal).divide(new BigDecimal(totalAmountValue), 3, BigDecimal.ROUND_HALF_UP).toString();

            allAmountResultInfo = new ChartViewInfo();
            allAmountResultInfo.value = amountTotalValue;
            allAmountResultInfo.label = "天津：" + new BigDecimal(TJInfo.amountTotal) + "元";
            allOrderAmountStatisticsInfoList.add(allAmountResultInfo);

            allAmountResultInfo = new ChartViewInfo();
            allAmountResultInfo.value = new BigDecimal("1").subtract(new BigDecimal(amountTotalValue)).toString();
            allAmountResultInfo.label = "河北：" + new BigDecimal(HBInfo.amountTotal) + "元";
            allOrderAmountStatisticsInfoList.add(allAmountResultInfo);

            mAmountPieChartView.setPieChartData(allOrderAmountStatisticsInfoList);

            statisticsDataInfo.allOrder = totalOrderValue;
            statisticsDataInfo.allAmount = totalAmountValue;
            mStatisticsDataView.setStatisticsViewData(statisticsDataInfo);
        }

        hideDialog();
    }

    private void requestDriverCarStatisticsInfo(int index, String date) {
        Map<String, String> map = new HashMap<>();
        map.put("dates", date);
        mModel.driverCarStatisticsInfoModel(this, map, false, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<DriverCarStatisticalInfo>>() {
            @Override
            public void onNext(CommonResponse<DriverCarStatisticalInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    driverCarResultList.put(index, commonResponse.getData());
                    int size = driverCarResultList.size();
                    if (size == 7) {
                        processDriverCarStatisticsInfo();
                    }
                } else {
                    showToast(date + "--" + commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(date + "--" + e.message);
            }
        });

    }

    private void processDriverCarStatisticsInfo() {
        List<IChartViewInfo> driverStatisticsInfoList = new ArrayList<>();
        List<IChartViewInfo> carStatisticsInfoList = new ArrayList<>();
        ChartViewInfo driverResultInfo;
        ChartViewInfo carResultInfo;
        DriverCarStatisticalInfo info = null;
        int resultSize = driverCarResultList.size();
        for (int i = 0; i < resultSize; i++) {
            carResultInfo = new ChartViewInfo();
            driverResultInfo = new ChartViewInfo();
            info = driverCarResultList.get(i);
            driverResultInfo.value = new BigDecimal(info.drivernow).add(new BigDecimal(info.yesdrivernow)).toString();
            driverResultInfo.label = dateList.get(i);
            driverStatisticsInfoList.add(driverResultInfo);

            carResultInfo.value = new BigDecimal(info.drivercarnow).add(new BigDecimal(info.yesdrivercarnow)).toString();
            carResultInfo.label = dateList.get(i);
            carStatisticsInfoList.add(carResultInfo);
        }
        mDriverBarChartView.setBarChartData(driverStatisticsInfoList);
        mCarBarChartView.setBarChartData(carStatisticsInfoList);

        if (info != null) {
            String totalDriver = new BigDecimal(info.drivertotal).add(new BigDecimal(info.yesdrivertotal)).toString();
            String totalCar = new BigDecimal(info.drivercartotal).add(new BigDecimal(info.yesdrivercartotal)).toString();

            statisticsDataInfo.allDriver = totalDriver;
            statisticsDataInfo.allCar = totalCar;
            mStatisticsDataView.setStatisticsViewData(statisticsDataInfo);
        }


    }


    @Override
    public CommonFragment createFragment() {
        return null;
    }


    @OnClick(R.id.activity_statistics_lastWeekTextView)
    public void lastWeek() {
        currentWeek += 1;
        initDateList();
    }

    @OnClick(R.id.activity_statistics_nextWeekTextView)
    public void nextWeek() {
        if (currentWeek != 1) {
            currentWeek -= 1;
            initDateList();
        } else {
            showToast("已经是最新一周数据了");
        }
    }

    private void showDialog() {
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void hideDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }
}
